<template>
    <div>
        <div class="top_nav flex">
            <div class="back flex-center w250 fs32 fw-bold" @click="backTop">
                <i class="icon-fanhui1 mar-r10 fs40"></i>
                素材库
            </div>
            <div class="next_art pad-lr10 flex-v-center flex-1 hfull fs32" @click="toNextArt">
                <span class="flex-1 w10 overflow">下一篇：{{next.title}}</span>
                <i class="icon-arrow-right fs24 fw-bold color-red"></i>
            </div>
        </div>
        <div class="mini_card_container">
            <div class="mini_card">
                <div class="avator">
                    <image :src="cardInfo.headImg" mode="" />
                </div>
                <div class="info">
                    <p>{{cardInfo.userName}}</p>
                    <span>{{cardInfo.userPhone}}</span>
                </div>
                <div class="btn" @click="scrollTopCard">联系TA</div>
            </div>
        </div>


        <div class="article" :class="{half_art: !hasLogin}">
            <div class="see_all" v-if="!hasLogin" @click="toLogin">点击查看全文</div>
            <div id="article">
                <div class="swiper_container" v-if="detail.imgUrls && detail.imgUrls.length">
                    <swiper 
                        :current="swiper.current" 
                        @change="swiperChange" 
                        class="swiper" 
                        :indicator-dots="true" 
                        :autoplay="true" 
                        :interval="5000" 
                        :duration="swiper.duration" circular>
                        <swiper-item class="swiper_item" v-for="(i, idx) in detail.imgUrls" :key="idx">
                            <image :src="i" mode="aspectFit" />
                        </swiper-item>
                    </swiper>
                </div>
                <h1>{{detail.title}}</h1>
                <div class="art_ad_container">
                    <div ref="artContext" class="content rich-context" :style="{minHeight: detail.originType == '05' ? '0' : '500rpx'}" v-html="detail.context"></div>
                    <div class="ad_list">
                        <div class="art_ad_item" v-for="(item, index) in advertList" :key="index" :style="{top: item.posY + 'px'}">
                            <adItem :id="item.id" :shareKey="shareKey"></adItem>
                        </div>
                    </div>
                </div>
            </div>
            <div class="advert_container mar-tb20" ref="advertContainer">
                <template v-if="advertInfo && advertInfo.id">
                    <adItem :item="advertInfo" :shareKey="shareKey" :canChange="canEdit" @change="chooseAdEdit" style="padding:0;"></adItem>
                </template>
                <template v-else>
                    <div v-if="canEdit" class="insert_ad flex-center flex-column" @click="insertAd">
                        <p class="flex-center color-red mar-b20">
                            <i class="icon-plus mar-r10"></i>
                            插入我的广告
                        </p>
                        <span class="color-999">这个按钮别人看不到</span>
                    </div>
                </template>
            </div>
            <button v-if="mixinIsDevRunTime" style="background: skyblue" class="mar-tb20" @click="testShareArt('00')">测试分享</button>
            <div class="view">
                <span>阅读</span>
                <span>{{detail.viewCnt}}</span>
            </div>
            <div class="op">
                <!-- <div class="btn">意见反馈</div> -->
                <div></div>
                <div class="btn flex-center color-ccc" :class="{'color-red': allInfo.hasPraise}" @click="toPraise">
                    <i v-if="allInfo.hasPraise" class="icon-dianzan_kuai color-red fs34 mar-r20"></i>
                    <i v-else class="icon-dianzan fs34 mar-r20"></i>
                    赞
                    <span class="mar-l10">{{detail.praiseCnt}}</span>
                </div>
            </div>
        </div>

        

        <div class="card_info" ref="cardInfo">
            <div class="card_avator">
                <image :src="cardInfo.headImg" mode="" />
            </div>
            <div class="user_name fs36 fw-bold color-fff mar-b30 flex-center">{{cardInfo.userName}}</div>
            <div class="btns">
                <div class="btn" @click="callPhoneNum">
                    <i class="icon-tel-solid"></i>
                    <span>打电话</span>
                </div>
                <div class="btn" @click="showQrcode">
                    <i class="icon-qrcode"></i>
                    <span>微信二维码</span>
                </div>
            </div>
        </div>
        <!-- <template v-else>
            <div v-if="canEdit" @click="showMyCard" class="insert_ad flex-center flex-column mar-t30">
                <p class="flex-center color-red mar-b20">
                    <i class="icon-plus mar-r10"></i>
                    添加我的名片
                </p>
                <span class="color-999">这个按钮别人看不到</span>
            </div>
        </template> -->



        <div class="tuijian">
            <div class="title">推荐阅读</div>
            <div class="list">
                <articleItem 
                    v-for="(item, index) in others" 
                    @click="toOtherArt(item)"
                    :item="item" :key="index"></articleItem>
            </div>
        </div>

        <div v-if="showChangeMyBtn && shareKey" class="change_my" >
            <div class="change_my_card" @click="changeMyCard">
                <p> 换成我名片 </p>
                <span>并转发该文章</span>
            </div>
            <div class="change_my_ad" @click="changeMyAd">
                <p> 换成我的广告 </p>
                <span>并转发该文章</span>
            </div>
        </div>

        <div class="wfull h200"></div>

        <div v-if="canEdit" class="float_btns">
            <div class="btn_item" @click="toEdit">
                <i class="icon-edit"></i>
                <p>编辑</p>
            </div>
            <div class="btn_item" @click="shareCopy">
                <i class="icon-pengyouquan"></i>
                <p>复制配文</p>
            </div>
            <div class="btn_item" @click="createPoster">
                <i class="icon-tupian"></i>
                <p>海报</p>
            </div>
        </div>
        <pub-timeline-tip ref="timelineTip"></pub-timeline-tip>

        <uni-popup ref="wxQrcode" type="center">
            <div class="w600 pad20" style="background: #fff; border-radius: 20rpx">
                <image class="wfull" :src="cardInfo && cardInfo.wxacodeUrl" mode="widthFix" />
            </div>
        </uni-popup>

        <setDynamic ref="setDynamic"></setDynamic>
		<adSelecter ref="adSelecter" type="文章" adPosPick></adSelecter>
		<createPoster ref="createPoster"></createPoster>
		<shareConfig ref="shareConfig" :detail="detail" :advertInfo="advertInfo"></shareConfig>
		<gzhPopup ref="gzhPopup"></gzhPopup>

    </div>
</template>

<script> 
import articleItem from '@/components/pages/article-item.vue'
import adSelecter from '@/components/pages/adSelecter'
import adItem from '@/components/pages/adItem'
import { getDynamicInfo, praiseDynamic, editDynamicIndustrys, getDynamicIndustrys, userHisLeave, updateShareTemp  } from '@/request/art'
import createPoster from '@/components/pages/createPoster'
import shareConfig from '@/components/pages/shareConfig'
import gzhPopup from '@/components/pages/gzh-popup'
import setDynamic from '@/components/pages/setDynamic'
import { listerPageClose, navSendBeacon } from '@/utils/pageClose'


export default {
    components: {
        shareConfig,
        createPoster,
        articleItem,
        adSelecter,
        adItem,
        gzhPopup,
        setDynamic
    },
    data() {
        return {
            nextArtIndex: 0, //第几个“下一篇，计算返回素材库返回几个页面用的”
            from: '', // myMaterial从我的来的， pubMaterialEditSuccess 从公共素材库编辑成功成为自己的文章 autoAd:自动滚动到广告位置，并且弹出更换广告

            swiper: {
                current: 0,
                duration: 500
            },

            shareKey: '', //分享key

            dynamicId: '', //文章id
            detail: {}, //文章详情
            next: {}, //下一篇
            others: [], //推荐
            allInfo: {}, //接口返回的所有详情
            advertList: [], //富文本里解析出来的广告列表

            advertInfo: {}, //广告详情       
            shareCardInfo: null, //名片
            readTimer: null, //阅读时长

            showChangeMyBtn: false, //换成我的名片，5秒钟后才显示
        }
    },         
    computed: {
        canEdit() {
            return !this.shareKey
        },
        hasLogin() {
            return !!this.$store.state.user.account.token
        },
        cardInfo() {
            if(this.shareKey) {
                return this.shareCardInfo || {}
            } else {
                return this.$store.state.user.userInfo || {}
            }
        }
    },    
    async onLoad(options) {
        console.log(this.$refs.adSelecter);
        this.nextArtIndex = +(options.nextArtIndex || 0)
        if(options.from) this.from = options.from;

        if(options.shareKey) {
            this.shareKey = options.shareKey;
            setTimeout(() => {
                this.showChangeMyBtn = true
            }, 5000)
        }

        setTimeout(async () => {
            this.dynamicId = options.id
            await this.getDetail()
            this.uploadReadTime()

            this.$refs.shareConfig.init({
                ...options,
                dynamicId: this.dynamicId
            }).then(rst => {
                console.log(rst);
                this.shareCardInfo = rst.shareCardInfo
                this.advertInfo = rst.advertInfo
            })
        })

        // 监听浏览器关闭事件
        listerPageClose(() => {
            navSendBeacon({
                token: this.$store.state.user.account.token,
                hisId: this.detail.hisId, 
            })
        })
    },
    onHide() {
        clearInterval(this.readTimer)
        this.userHisLeave()
    },
    onUnload() {
        clearInterval(this.readTimer)
        this.userHisLeave()
    },
    onShow() {
        if(this.dynamicId) {
            if(!this.shareKey) {
                this.getDetail()
                // this.getDefaultAd()
            }
        }
        if(this.allInfo.hisId) {
            this.uploadReadTime()
        }
    },
    methods: {
        async toNextArt() {
            await this.$toLogin()
            await this.checkGZHstatus()
            if(!this.next.id) return;
            this.$navigate.to(`/pages/material/detail?id=${this.next.id}&nextArtIndex=${this.nextArtIndex + 1}`)
        },
        async backTop() {
            await this.$toLogin()
            await this.checkGZHstatus()
            // 公共素材库编辑后跳转的详情为用户素材，上一个界面是编辑界面，故返回是需要跳转回公素材库
            if(this.from == 'pubMaterialEditSuccess') {
                return this.$navigate.to('/pages/material')
            }
            // 被刷新后，历史记录不存在了，需要返回到首页
            let prePageFullPath = this.$prePage() && this.$prePage().__page__.fullPath || ''
            if(!prePageFullPath) {
                this.$navigate.to('/pages/material')
            }
            // 根据下一篇的数量计算返回素材库应该后退的步数
            uni.navigateBack({
                delta: this.nextArtIndex + 1,
                fail() {
                    if(this.detail.userId && this.detail.userId != '0') {
                        this.$navigate.to('/pages/user/myMaterial')
                    } else {
                        this.$navigate.to('/pages/material')
                    }
                }
            })
        },
        getDetail() {
            return new Promise(async (resolve, reject) => {
                getDynamicInfo({
                    frontKey: this.shareKey || void 0,
                    dynamicId: this.dynamicId
                }).then(res => {
                    this.detail = res.data.dynamic
                    this.others = res.data.others
                    this.next = res.data.next || {}
                    this.allInfo = res.data

                    uni.setNavigationBarTitle({ title: res.data.dynamic.title })

                    if(this.detail.userId == this.$store.state.user.userInfo.userId && (!this.detail.industryNames || this.detail.industryNames.length == 0)) {
                        this.$refs.setDynamic.open({dynamicId: this.dynamicId})
                    }
                    this.formatAdvert()

                    if(this.from == 'autoAd') {
                        this.scrollTopAd()
                    }
                    resolve()         
                })
            })
        },
        formatAdvert() {
			setTimeout(() => {
				this.$nextTick(() => {
					let artStr = this.$refs.artContext.innerHTML
					let adReg = /id="rich_advert_(\d+)(_temp_.*?_)"/ig
					let advertList = []
					var res = null
					while(res = adReg.exec(artStr)) {
						advertList.push({
							id: res[1],
							posY: document.getElementById('rich_advert_' + res[1] + res[2]).offsetTop
						})
					}
					this.advertList = advertList
				})
			}, 500)
		},
        toPraise() {
            // 目前点赞不能取消
            if(this.allInfo.hasPraise) return
            praiseDynamic({
                dynamicId: this.dynamicId
            }).then(res => {
                this.allInfo.hasPraise = Number(!this.allInfo.hasPraise)
                if(this.allInfo.hasPraise) {
                    this.detail.praiseCnt += 1
                } else {
                    this.detail.praiseCnt -= 1
                }
            })
        },
        shareCopy() {
            this.$refs.timelineTip.open(this.detail.title)
        },
        async toEdit() {
            await this.$checkVip('编辑文章是会员特权，是否去开通会员')
            this.$navigate.to(`/pages/create/editArticle?id=${this.dynamicId}` + (this.from == 'myMaterial' ? '&form=myMaterial' : "") )
        },
        testShareArt() {
            this.$refs.shareConfig.shareArt('00')
        },
        swiperChange(e) {
            this.swiper.current = e.detail.current
        },
        createPoster() {
            this.swiper.duration = 0
            this.swiper.current = 0
            this.$nextTick(() => {
                this.$refs.createPoster.create({
                    type: 'article',
                    linkQrcode: this.$refs.shareConfig.getShareLink() + '&isPoster=1',
                }).then(() => {
                    this.swiper.duration = 500
                    this.$refs.shareConfig.shareArt('poster')
                })
            })
        },
        chooseAdEdit(type) {
            if(type == 'change'){
                this.insertAd()
            } else if(type == 'delete'){
                this.advertInfo = {}
            }
        },
        async insertAd() {
            this.$refs.adSelecter.open().then(rst => {
                this.advertInfo = rst
            })
        },
        scrollTopCard() {
            console.log(123);
            uni.pageScrollTo({
                scrollTop: this.$refs.cardInfo.offsetTop - 100,
                duraction: 1
            })
        },
        scrollTopAd() {
            this.$nextTick(() => {
                setTimeout(() => {
                    uni.pageScrollTo({
                        scrollTop: this.$refs.advertContainer.offsetTop - 100,
                        duraction: 1,
                        success: () => {
                            this.$refs.adSelecter.open().then(rst => {
                                this.advertInfo = rst
                            })
                        }
                    })
                }, 100)
            })
        },
        callPhoneNum() {
            if(!this.cardInfo.userPhone) return this.$interact.toast('该用户没有设置手机号')
            uni.makePhoneCall({
                phoneNumber: this.cardInfo.userPhone
            })
        },
        showQrcode() {
            if(!this.cardInfo?.wxacodeUrl) return this.$interact.toast('该用户没有设置二维码')
            this.$refs.wxQrcode.open()
        },
        async changeMyCard() {
            await this.$toLogin()
            await this.checkGZHstatus()
            // await this.checkVip()
            location.replace('/pages/material/detail?id=' + this.dynamicId)
        },
        async changeMyAd() {
            await this.$toLogin()
            await this.checkGZHstatus()
            // await this.checkVip()
            location.replace('/pages/material/detail?from=autoAd&id=' + this.dynamicId)
        },

        async toOtherArt(item) {
            await this.$toLogin()
            await this.checkGZHstatus()
            this.$navigate.to('/pages/material/detail?id=' + item.id)
        },
        uploadReadTime() {
            clearInterval(this.readTimer)
            this.readTimer = setInterval(() => {
                this.userHisLeave()
            }, this.mixinIsDevRunTime ? 150000 : 5000) 
        },
        userHisLeave(isFetch) {
            if(!this.shareKey) return;         
            if(this.$store.state.user.account.token && this.allInfo.hisId) {
                userHisLeave({ hisId: this.allInfo.hisId }, { loadingIcon: false})
            }
        },
        toLogin() {
            this.$toLogin()
        },
        checkGZHstatus() {
            return new Promise((resolve, reject) => {
                if(this.$store.state.user.userInfo.subscribeFlag == '01' || this.canEdit) { //有关注过公众号或者已经进入可编辑状态
                    resolve()
                } else {
                    this.$refs.gzhPopup.open({
                        refType: '00',
                        refId: this.dynamicId,
                    })
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
.top_nav{
    width: 100%;
    height: 90rpx;
    background: #fff;
    border-bottom: 1px solid #e5e5e5;
    position: sticky;
    top: 0;
    z-index: 50;
    .back{
        background: @mainColor;
        height: 100%;
        color: #fff;
        flex-shrink: 0;
    }
    .next_art{
        background: #f9f9f9;
    }
}

.mini_card_container{
    background: #fff;
    padding: 30rpx 30rpx 0;
    .mini_card{
        width: 100%;
        height: 140rpx;
        border-radius: 10rpx;
        margin: 30rpx auto 0;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        padding: 0 20rpx;
        .avator{
            width: 100rpx;
            height: 100rpx;
            background: #fff;
            border-radius: 50%;
            image{
                width: 100%;
                height: 100%;
            }
        }
        .info{
            flex: 1;
            padding: 0 20rpx;
            width: 10px;
            p{
                font-size: 32rpx;
                font-weight: bold;
                margin-bottom: 10rpx;
            }
            span{
                font-size: 28rpx;
                color: #999;
            }
        }
        .btn{
            width: 120rpx;
            height: 50rpx;
            background: @mainColor;
            color: #fff;
            font-size: 26rpx;
            .align(center);
            border-radius: 25rpx;
        }
    }
}

.article{
    padding: 30rpx 0;
    background: #fff;
    .swiper_container{
        width: 100%;
        height: 920rpx;
        margin-bottom: 20rpx;
        .swiper,.swiper_item, image{
            width: 100%;
            height: 100%;
        }
    }
    h1{
        font-size: 40rpx;
        font-weight: bold;
        line-height: 60rpx;
        margin-bottom: 30rpx;
        padding: 0 30rpx;
    }
    .art_ad_container{
        background: #fff;
        position: relative;
        padding: 0 30rpx;
        .ad_list{
            .art_ad_item{
                position: absolute;
                width: 690rpx;
                height: 320rpx;
                padding: 10rpx 0;
                z-index: 10;
            }
        }
    }
    
    .view{
        width: 100%;
        padding: 50rpx 30rpx 30rpx 30rpx;
        border-bottom: 1px solid #e5e5e5;
        span{
            margin-right: 20rpx;
            color: #ccc;
        }
    }
    .op{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        padding: 30rpx 30rpx 10rpx;
        .btn{
            height: 80rpx;
            line-height: 80rpx;
            border-radius: 40rpx;
            border: 1px solid #ddd;
            padding: 0 30rpx;
            &:first-child{
                border: 0;
                padding: 0 40rpx;
                background: #f7f7f7;
                color: #aaa;
            }
        }

    }
}

.advert_container{
    padding: 0 30rpx;
    position: relative;
    .icon-settings{
        width: 60rpx;
        height: 60rpx;
        font-size: 26rpx;
        color: #aaa;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 10;
        .align(center);
    }
}
.insert_ad{
    width: 690rpx;
    height: 200rpx;
    border: 1px dashed @mainColor;
    border-radius: 20rpx;
    background: #ffeeef;
    margin-left: auto;
    margin-right: auto;
}

.tuijian{
    width: 690rpx;
    margin: 30rpx auto;
    background: #fff;
    padding: 30rpx;
    border-radius: 15rpx;
    .title{
        font-size: 34rpx;
        line-height: 60rpx;
        color: #999;
        margin-bottom: 20rpx;
        position: relative;
        &::before{
            content: "";
            width: 6rpx;
            height: 50rpx;
            background: @mainColor;
            position: absolute;
            left: -30rpx;
            top: 5rpx;
        }
    }
}

.float_btns{
    display: flex;
    align-items: center;
    width: 100%;
    height: 100rpx;
    background: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    border-top: 1px solid #ddd;
    z-index: 10;
    .btn_item{
        flex: 1;
        .align(center, column);
        position: relative;
        &::after{
            content: "";
            width: 1rpx;
            height: 50rpx;
            top: 25rpx;
            right: 0;
            position: absolute;
            background: #ddd;
        }
        i{
            font-size: 30rpx;
        }
        p{
            font-size: 28rpx;
        }
    }
}

.card_info{
    width: 690rpx;
    margin: 80rpx auto 0;
    height: 300rpx;
    background: @mainColor;
    position: relative;
    border-radius: 20rpx;
    padding-top: 100rpx;
    .gradient(#fe532d, #e13040, to bottom);
    .card_avator{
        width: 150rpx;
        height: 150rpx;
        position: absolute;
        top: -70rpx;
        border-radius: 50%;
        overflow: hidden;
        left: 50%;
        transform: translateX(-50%);
        background: #fff;
        padding: 10rpx;
        image{
            width: 100%;
            height: 100%;
            border-radius: 50%;
        }
    }
    .btns{
        width: 100%;
        padding: 0 30rpx;
        display: flex;
        justify-content: space-between;
        .btn{
            width: 300rpx;
            height: 80rpx;
            background: #fff;
            border-radius: 40rpx;
            .align(center);
            i{
                margin-right: 10rpx;
            }
        }
    }
}

.change_my{
    display: flex;
    position: fixed;
    bottom: 40rpx;
    left: 0;
    width: 100%;
    justify-content: space-between;
    padding: 0 30rpx;
    display: flex;
    z-index: 10;

    div{
        width: 330rpx;
        height: 90rpx;
        color: #FFF;
        background: @mainColor;
        border-radius: 45rpx;
        .align(center, column);
        z-index: 100;
        p{
            font-weight: bold;
            font-size: 32rpx;
        }
        span{
            font-size: 24rpx;
        }
    }

}


.edit_ad_drawer{
    /deep/ .uni-drawer__content{
        background: transparent;
    }
    .edit_choose{
        width: 100%;
        height: 100%;
        padding: 200rpx 30rpx 0 0;
        display: flex;
        justify-content: flex-end;
        .choose_item{
            width: 140rpx;
            height: 160rpx;
            background: #fff;
            border-radius: 10rpx;
            padding: 0 15rpx;
            position: relative;
            &::before{
                content: "";
                width: 0;
                height: 0;
                position: absolute;
                top: -10rpx;
                right: 25rpx;
                border-bottom: 10rpx solid #fff;
                border-left: 10rpx solid transparent;
                border-right: 10rpx solid transparent;
            }
            p{
                height: 70rpx;
                line-height: 70rpx;
                border-bottom: 1px solid #eee;
                text-align: center;
            }
        }
    }
}



.half_art{
    height: 800rpx;
    overflow: hidden;
    position: relative;
    overflow: hidden;
    .see_all{
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        width: 260rpx;
        height: 60rpx;
        border-radius: 30rpx;
        border: 1px solid #1787f3;
        bottom: 25rpx;
        font-weight: bold;
        z-index: 120;
        color: #1787f3;
        background: rgba(255, 255, 255, 0.8);
        .align(center);

    }
    &::after{
        content: "";
        position: absolute;
        bottom: -40rpx;
        left: 0;
        width: 100%;
        height: 100rpx;
        background: #fff;
        box-shadow: 0 -60rpx 60rpx #fff;
        z-index: 100;
    }
}

</style>